package com.navi.job.service;

import com.alibaba.fastjson.JSONObject;
import com.navi.SpringContext;
import com.navi.util.LogUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import static com.navi.constant.GenericDef.RETURN_FAISE;
import static com.navi.constant.GenericDef.RETURN_REWORK_THISCASE;
import static com.navi.constant.GenericDef.RETURN_SUCCESS;


@Slf4j
//String[] 0 正常，1 error  2.只需要重跑
public class MainCallable implements Callable<Integer> {

    private String queueName;

    private String tableName;

    private List<JSONObject> jsonObjList;

    private Channel channel = null;

    private Map<GetResponse, String> responseMap = null;

    private  String limit_time;

    private String deleteInsert;

    private String jobBatchId;

    private MainService mainService = null;

    public MainCallable(String queueName, String tableName, List<JSONObject> jsonObjList, Channel channel, Map<GetResponse, String> responseMap, String limit_time, String deleteInsert, String jobBatchId) {
        this.queueName = queueName;
        this.tableName = tableName;
        this.jsonObjList = jsonObjList;
        this.channel = channel;
        this.responseMap = responseMap;
        this.limit_time =  limit_time;
        this.deleteInsert =  deleteInsert;
        this.jobBatchId = jobBatchId;
        mainService = SpringContext.getBean(MainService.class);
    }


    @Override
    public Integer call() throws Exception {
        //0 ok； 1 error； 2 重跑当前所有；  3 重试当前
        int res=3;
        log.info("线程任务[{}]开始, json_cnt: {}", tableName, jsonObjList.size());

        try {
//            res=!(tableName.contains("pds")||tableName.contains("mds"))
//                    ? mainService.subMainProc(queueName, tableName, jsonObjList, channel, responseMap, limit_time, deleteInsert, jobBatchId)
//                    :mainService.subMainProcForPds(queueName, tableName, jsonObjList, channel, responseMap, limit_time, deleteInsert, jobBatchId);
            res=mainService.subMainProcForPds(queueName, tableName, jsonObjList, channel, responseMap, limit_time, deleteInsert, jobBatchId);

            while (res==RETURN_REWORK_THISCASE){
                log.info("线程任务[{}]出现 Redis异常，重跑当前线程。",tableName);
                res=mainService.subMainProcForPds(queueName, tableName, jsonObjList, channel, responseMap, limit_time, deleteInsert, jobBatchId);
            }
        } catch (Exception e) {
            log.error("线程任务[{}]出现 未处理异常 ,错误原因:{}", tableName, LogUtil.stackTraceToString(e));
            return RETURN_FAISE;
        }


        return res;
    }

}
